package com.bestcem.xm.om.grpc.client;

import com.alibaba.fastjson.JSON;
import com.bestcem.bp.xm.user.grpc.v1.services.*;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.common.core.uitls.GrpcDateUtil;
import com.bestcem.xm.om.entity.readonly.UserOrganization;
import com.bestcem.xm.om.enums.BooleanStatusEnum;
import com.bestcem.xm.om.service.dto.SampleCodeDTO;
import com.zy.dp.proto.base.v1.Code;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 倍市得 user 模块相关rpc接口客户端
 *
 * @author zq.ding <zq.ding@idiaoyan.com>
 * @version v1.0
 * @date 2021/12/27 15:35
 */
@Slf4j
@Service
public class OmOrgGrpcService {
    @GrpcClient(GrpcClientNames.DS_USER)
    private OrgServiceGrpc.OrgServiceBlockingStub stub;

    private static final String ORG_CREATE_ERROR_MSG = "[OM] 租户管理创建租户失败 org:{}";

    /**
     * 根据id获取租户信息
     *
     * @param id
     * @return com.bestcem.xm.user.grpc.v1.services.Organization
     * @author zhangfeng <feng.zhang@idiaoyan.com>
     * @date 2022/6/6 15:46
     */
    @Nullable
    public Organization getByIdOrCode(String id) {
        GetOrgByIdOrCodeRequest.Builder builder = GetOrgByIdOrCodeRequest.newBuilder();
        builder.setId(id);
        GetOrgByIdOrCodeResponse response = stub.getOrgByIdOrCode(builder.build());
        // 返回值处理
        if (Code.OK_VALUE == response.getStatus().getCodeValue()) {
            if (log.isInfoEnabled()) {
                log.info("[OM] user接口返回：getByIdOrCode");
            }
            return response.getOrg();
        } else {
            if (Code.ERROR_VALUE == response.getStatus().getCodeValue()) {
                log.error("[OM] 调用user接口[根据id查询机构信息]失败：dto:{} id:{}", response.getStatus().getMessage(), id);
            }
            return null;
        }
    }

    /**
     * 根据id更新租户信息
     *
     * @param org
     * @return boolean
     * @author zhangfeng <feng.zhang@idiaoyan.com>
     * @date 2022/6/20 17:23
     */
    public boolean updateOrganization(UserOrganization org) {
        try {
            UpdateOrgRequest.Builder builder = UpdateOrgRequest.newBuilder();
            builder.setId(org.getOrgId());
            OperateOrg.Builder orgBuilder = OperateOrg.newBuilder();
            if (Objects.nonNull(org.getStatus())) {
                orgBuilder.setStatusValue(org.getStatus());
            }
            if (Objects.nonNull(org.getIndustryId())) {
                orgBuilder.setIndustryId(org.getIndustryId());
            }
            if (Objects.nonNull(org.getAdminEmail())) {
                orgBuilder.setAdminEmail(org.getAdminEmail());
            }
            if (Objects.nonNull(org.getAdminPhone())) {
                orgBuilder.setAdminPhone(org.getAdminPhone());
            }
            if (Objects.nonNull(org.getName())) {
                orgBuilder.setName(org.getName());
            }
            if (Objects.nonNull(org.getPackageId())) {
                orgBuilder.setPackageId(org.getPackageId());
            }
            if (Objects.nonNull(org.getSmsPrice())) {
                orgBuilder.setSmsPrice(org.getSmsPrice());
            }
            if (Objects.nonNull(org.getFormalPackageId())) {
                orgBuilder.setFormalPackageId(org.getFormalPackageId());
            }
            if (Objects.nonNull(org.getFormalExpireTime())) {
                orgBuilder.setFormalExpireTime(GrpcDateUtil.getTimestamp(org.getFormalExpireTime()));
            }
            if (Objects.nonNull(org.getTrialPackageId())) {
                orgBuilder.setTrialPackageId(org.getTrialPackageId());
            }
            if (Objects.nonNull(org.getTrialExpireTime())) {
                orgBuilder.setTrialExpireTime(GrpcDateUtil.getTimestamp(org.getTrialExpireTime()));
            }
            if (Objects.nonNull(org.getDistribution())) {
                orgBuilder.setDistribution(org.getDistribution());
            }
            if (Objects.nonNull(org.getContractUrls())) {
                orgBuilder.addContractUrls(org.getContractUrls());
            }
            if (Objects.nonNull(org.getCrmStatus())) {
                orgBuilder.setCrmStatus(org.getCrmStatus());
            }
            if (Objects.nonNull(org.getSensitiveWordEnable())) {
                orgBuilder.setSensitiveWordEnable(BooleanStatusEnum.toBoolean(org.getSensitiveWordEnable()));
            }
            builder.setOrg(orgBuilder);

            UpdateOrgResponse response = stub.updateOrg(builder.build());
            if (Code.ERROR_VALUE == response.getStatus().getCodeValue()) {
                log.error("[OM] 调用user接口[更新机构信息]失败：dto:{} id:{}", response.getStatus().getMessage(), org.getOrgId());
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("[OM] 调用user接口[更新机构信息]失败：", e);
            return false;
        }
    }

    /**
     * 根据组织id或组织code查询机构信息
     *
     * @param orgId   组织id
     * @param orgCode 组织code
     * @return com.bestcem.bp.xm.user.grpc.v1.services.Organization
     * @author zhangfeng <feng.zhang@idiaoyan.com>
     * @date 2022/6/15 14:14
     */
    public Organization getByIdOrCode(String orgId, String orgCode) {
        GetOrgByIdOrCodeRequest.Builder builder = GetOrgByIdOrCodeRequest.newBuilder();
        if (StringUtils.isNotEmpty(orgId)) {
            builder.setId(orgId);
        }
        if (StringUtils.isNotEmpty(orgCode)) {
            builder.setCode(orgCode);
        }
        try {
            GetOrgByIdOrCodeResponse response = stub.getOrgByIdOrCode(builder.build());
            if (Code.OK_VALUE == response.getStatus().getCodeValue()) {
                if (log.isInfoEnabled()) {
                    log.info("[OM] user返回：{}", response.getOrg());
                }
                return response.getOrg();
            }
        } catch (Exception e) {
            log.error("[OM] 调用user接口[查询机构信息]失败 orgId:{} ", orgId, e);
        }
        return null;
    }

    public List<SampleCodeDTO> listIndustrySampleCodes(Collection<String> codes) {
        ListIndustrySampleCodesRequest.Builder builder = ListIndustrySampleCodesRequest.newBuilder();
        builder.addAllCodes(codes);
        ListIndustrySampleCodesResponse response = stub.listIndustrySampleCodes(builder.build());
        // 返回值处理
        if (Code.OK_VALUE == response.getStatus().getCodeValue()) {
            if (log.isInfoEnabled()) {
                log.info("[OM] user接口返回：{}", response.getCodesList());
            }
            return response.getCodesList().stream().map(o -> {
                SampleCodeDTO sampleCodeDTO = new SampleCodeDTO();
                sampleCodeDTO.setOrgId(o.getOrgId());
                sampleCodeDTO.setOrgCode(o.getOrgCode());
                return sampleCodeDTO;
            }).collect(Collectors.toList());
        } else {
            if (Code.ERROR_VALUE == response.getStatus().getCodeValue()) {
                log.error("[OM] 调用user接口[查询行业示例code列表]失败：dto:{} codes:{}", response.getStatus().getMessage(), JSON.toJSONString(codes));
            }
            return Collections.emptyList();
        }
    }
}
